package cn.cuiliangpeng.basic.service.impl;

import cn.cuiliangpeng.basic.consts.RedisConstants;
import cn.cuiliangpeng.basic.domain.dto.RegisterDto;
import cn.cuiliangpeng.basic.exception.BusinessException;
import cn.cuiliangpeng.basic.exception.ErrorCode;
import cn.cuiliangpeng.basic.service.IVerifyCodeService;
import cn.cuiliangpeng.basic.utils.AjaxResult;
import cn.cuiliangpeng.basic.utils.StrUtils;
import cn.cuiliangpeng.basic.utils.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 图形验证码
     * @param imageCodeKey
     * @return
     */
    @Override
    public AjaxResult verifyCode(String imageCodeKey) {
        //1.生成随机字符串
        String code = StrUtils.getComplexRandomString(4);
        //2.生成随机图形验证码
        String verifyCode = VerifyCodeUtils.VerifyCode(115, 40, code);
        //3.保存到redis 设置过期时间
        redisTemplate.opsForValue().set(imageCodeKey,code,5, TimeUnit.MINUTES);
        //4.返回图形验证码给前端
        return AjaxResult.me().setResultObj(verifyCode);
    }

    @Override
    public AjaxResult sendSmsCode(RegisterDto dto) {
        //1.校验图形验证码是否正确
        //2.从redis中获取图形验证码
        String imageCode = (String) redisTemplate.opsForValue().get(dto.getImageCodeKey());
        if (imageCode==null){ //没有（业务异常）
            throw new BusinessException(ErrorCode.IMAGE_CODE_TIME_OUT.getCode());
        }
        //3.通过前端传递的uuid从redis中获取，和传递过来的图形验证码进行比对（忽略大小写）
        if (!imageCode.equalsIgnoreCase(dto.getImageCode())){
            throw new BusinessException(ErrorCode.IMAGE_CODE_ERROR.getCode());
        }
        //4.通过手机号拼接业务键拼接为key
        String smsKey=dto.getPhone()+ RedisConstants.REGISTER_KEY;
        System.out.println(smsKey);
        //5.通过手机号拼接业务键去redis中查询
        String smsCodeValue = (String) redisTemplate.opsForValue().get(smsKey);
        //6.已过期或者第一次来获取验证码
        String smsCode;
        if (smsCodeValue==null){//第一次来
            //6.1生成验证码
            smsCode  = StrUtils.getComplexRandomString(6);
            //6.2发送短信
            /*SmsUtils.sendSms(dto.getPhone(),"验证码："+smsCode+",请在3分种内使用验证码");*/
            System.out.println("本次获取的验证码>>>>>>" + smsCode);
        }else {//过期
            Long sendTime = Long.valueOf(smsCodeValue.split(":")[1]);
            if(!(System.currentTimeMillis() - sendTime >= 1*60*1000)){
                throw new BusinessException(ErrorCode.SMSCODE_ERROR.getCode());
            }
            //6.3发送老的验证码
            smsCode =  smsCodeValue.split(":")[0];
            //6.4发送短信
            System.out.println("本次获取的验证码>>>>>>" + smsCode);
        }
        //7保存redis刷新过期时间
        redisTemplate.opsForValue().set(smsKey, smsCode + ":"+System.currentTimeMillis(), 3, TimeUnit.MINUTES);
        return AjaxResult.me();
    }
}
